from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User
from django.utils.crypto import get_random_string

class UserAdmin(BaseUserAdmin):
    list_display = ('username', 'real_name', 'role', 'email', 'is_active')
    list_filter = ('role', 'is_active')
    search_fields = ('username', 'real_name', 'email')

    def save_model(self, request, obj, form, change):
        if not change:
            # 新建用户时自动设置用户名和密码
            if obj.role == 'student' and not obj.username.startswith('sd'):
                obj.username = 'sd' + get_random_string(6, allowed_chars='0123456789')
            elif obj.role == 'teacher' and not obj.username.startswith('st'):
                obj.username = 'st' + get_random_string(6, allowed_chars='0123456789')
            obj.set_password('123456')
        super().save_model(request, obj, form, change)

admin.site.register(User, UserAdmin) 